/*
 * @Author: Zhang Kai
 * @Date: 2021-10-18 16:32:22
 * @LastEditors: mayijun
 * @LastEditTime: 2022-06-08 15:01:34
 * @FilePath: /metricsx-standard-ui/src/utils/http/index.ts
 */
import URL from './url';
import axios from 'axios';
import custom_http from '../saber-http/custom-axios';
import SaberHTTP from '../saber-http/SaberHttp';
import qs from 'qs';

const http = custom_http as SaberHTTP & {
  get: any;
  post: any;
  put: any;
  delete: any;
};

const userCode = 'superadmin';
const orgCode = '10000';

// todo： 这些代码不应该放到这里, 应该放到中间件中
if (process.env.VUE_APP_LOCAL_COOKIE === 'development') {
  http._axios.defaults.headers['userCode'] = userCode;
  http._axios.defaults.headers['orgCode'] = orgCode;
  // todo: 我也临时在这添加代码 但是不应该放到这里
  // http._axios.defaults.headers['X_TENANT'] = 'eyJkZXBsb3lNb2RlIjoiU0hBUkUiLCJuYW1lc3BhY2UiOiJERUZBVUxUIiwib3JnQ29kZSI6ImRpZ2l0Zm9yY2UiLCJ0ZW5hbnRJZCI6MTAwMDAsInVzZXJBY2NvdW50IjoiYWRtaW4iLCJ1c2VyTmFtZSI6IueuoeeQhuWRmCJ9';
  http._axios.defaults.headers['X_TENANT'] = 'eyJkZXBsb3lNb2RlIjoiU0hBUkUiLCJuYW1lc3BhY2UiOiJERUZBVUxUIiwib3JnQ29kZSI6IjEwMDAwIiwidGVuYW50SWQiOjEwMDAwLCJ1c2VyQWNjb3VudCI6ImxpbmhlbmciLCJ1c2VyTmFtZSI6Iuael+aBkiJ9';
}

const getUrl = (
  path: string,
  queryParams: any,
  _method: string
): { path: string } => {
  const params = {
    ...(queryParams || ({} as any))
  };
  const url =
    process.env.VUE_APP_SERVERPATH +
    path.replace(/\{([^\\}]*(?:\\.[^\\}]*)*)\}/gm, (match, key) => {
      // eslint-disable-next-line no-param-reassign
      key = key.trim();

      if (params[key] !== undefined) {
        const value = params[key];
        delete params[key];
        return value;
      }
      console.warn('Please set value for template key: ', key);
      return '';
    });

  const paramStr = Object.keys(params)
    .map((key) => {
      return params[key] === undefined ? '' : `${key}=${params[key]}`;
    })
    .filter((id) => id)
    .join('&');

  if (paramStr) {
    // return `${url}?${paramStr}`;
    return { path: `${url}?${paramStr}` };
  }

  return { path: url };
};

interface paramsType {
  url: string;
  method: any;
  data?: any;
  params?: any;
  config?: any;
}

// todo： 这些代码不应该放到这里
const downLoadFile = ({ url, method, data, params, config }: paramsType) => {
  // 响应类型：arraybuffer, blob
  axios({
    method,
    url: process.env.VUE_APP_SERVERPATH + url,
    data,
    params,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json; application/octet-stream',
      userCode,
      orgCode
    },
    ...config
  })
    .then((resp) => {
      const headers = resp.headers;
      const contentType = headers['content-type'];
      if (!resp.data) {
        console.error('响应异常：', resp);
        return false;
      } else {
        const blob = new Blob([resp.data], { type: contentType });

        const contentDisposition = resp.headers['content-disposition'];
        let fileName = 'unknown';
        if (contentDisposition) {
          fileName = window.decodeURI(
            resp.headers['content-disposition'].split('=')[1]
          );
        }
        console.log('文件名称：', fileName);
        if ('download' in document.createElement('a')) {
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob); // 创建下载的链接
          link.download = fileName; // 下载后文件名
          link.style.display = 'none';
          document.body.appendChild(link);
          link.click(); // 点击下载
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          document.body.removeChild(link); // 下载完成移除元素
        } else {
          // IE10+下载
          (window.navigator as any).msSaveBlob(blob, fileName);
        }
      }
    })
    .catch(function (error) {
      console.log(error);
    });
};

export { http, URL, getUrl, userCode, orgCode, downLoadFile };

export default http;
